package com.token.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.token.sql.AbstractTableBean;
import com.token.sql.PrepareSql;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

/**
 * 生成JSONObject和JSONArray
 *
 * @author chenjianxiong 2020/4/6
 */
public class JsonGenerator {

    /**
     * 返回Json
     *
     * @param bean TableBean类
     * @param json JSONObject
     * @return JSONObject
     * @throws Exception 抛出错误
     */
    public static JSONObject toJson(AbstractTableBean bean, JSONObject json) throws Exception {
        Vector<String> vec = bean.getFields();
        Method m;
        for (String field : vec) {
            m = bean.getClass().getMethod("get" + field);
            json.put(field, m.invoke(bean));
        }
        return json;
    }


    /**
     * 返回一个类中的成员变量为一个JSON
     * @param c 类
     * @param o 对象
     * @return JSON
     * @throws Exception 抛出错误
     */
    public static JSONObject toJson(Class<?> c,Object o) throws Exception {
        JSONObject json = new JSONObject();
        Field[] fields = c.getDeclaredFields();
        Method m;
        for (Field field : fields) {
            String varName = field.getName();
            char[] cs = varName.toCharArray();
            cs[0] -= 32;
            String mName = "get" + String.valueOf(cs);

            try {

                m = c.getMethod(mName);
                json.put(varName, m.invoke(o));

            } catch (Exception no) {
                System.out.println("--->无函数：" + mName + no.toString());
            }
        }
        return json;
    }

    /**
     * 返回新的Json
     *
     * @param bean TableBean类
     * @return JSONObject
     * @throws Exception 抛出错误
     */
    public static JSONObject toJson(AbstractTableBean bean) throws Exception {
        JSONObject json = new JSONObject();
        return toJson(bean, json);
    }

    /**
     * 返回一行结果集的JSON
     * @param rs 当前行的结果集
     * @return JSONObject
     * @throws SQLException 抛出错误
     */
    public static JSONObject toJson(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        JSONObject jsonObj = new JSONObject(); // json对象
        // 遍历每一列
        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnLabel(i);
            if (!columnName.equalsIgnoreCase("JsonNode")) {
                jsonObj.put(columnName, rs.getObject(i));
            }
        }
        return jsonObj;
    }

    /**
     * 将resultSet转化为JSON数组
     *
     * @param rs 结果集
     * @return JSONArray
     * @throws SQLException 抛出错误
     */
    public static JSONArray toJsonArray(ResultSet rs) throws SQLException {
        // json数组
        JSONArray array = new JSONArray();
        // 获取列数
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        // 遍历ResultSet中的每条数据
        while (rs.next()) {
            JSONObject jsonObj = new JSONObject();
            // 遍历每一列
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                String value = rs.getString(columnName);
                jsonObj.put(columnName, value);
            }
            array.add(jsonObj);
        }
        return array;
    }

    /**
     * 返回JSONArray
     *
     * @param bean       Bean 对象
     * @param fieldName  where 字段名
     * @param fieldValue 字段值
     * @return JSONArray 返回JSON
     * @throws SQLException 抛出错误
     */
    public static JSONArray toJsonArray(AbstractTableBean bean, String fieldName, String fieldValue) throws SQLException {
        JSONArray arr = new JSONArray();
        PrepareSql ps = new PrepareSql(bean.getIntegrateSql());
        ps.setPrepare(bean.selectCode().append(" where ").append(fieldName).append("=?"));
        ps.setPstValue(1, fieldValue);
        ResultSet rs = ps.executeQuery();
        Vector<String> vec = bean.getFields();
        if (rs.next()) {
            JSONObject json;
            do {
                json = new JSONObject();
                for (String key : vec) {
                    json.put(key, rs.getObject(key));
                }
                arr.add(json);
            } while (rs.next());
        }
        rs.close();
        ps.close();
        return arr;
    }
}
